package team.seekers.hula.record.wind.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import team.seekers.hula.common.entity.PageResult;
import team.seekers.hula.common.entity.enums.WindSpaceTypeEnum;
import team.seekers.hula.common.entity.enums.WindTypeEnum;
import team.seekers.hula.course.course.entity.vo.CourseManageListVO;
import team.seekers.hula.course.course.service.CourseManageService;
import team.seekers.hula.course.resource.sectionContentComment.service.SectionContentCommentService;
import team.seekers.hula.course.resource.sectionTalk.service.SectionTalkService;
import team.seekers.hula.island.island.entity.vo.IslandListVO;
import team.seekers.hula.island.island.service.IslandService;
import team.seekers.hula.island.post.service.IslandPostService;
import team.seekers.hula.record.history.entity.vo.HistoryInfoVO;
import team.seekers.hula.record.history.entity.vo.HistoryUserVO;
import team.seekers.hula.record.history.service.HistoryService;
import team.seekers.hula.record.wind.entity.dao.WindDO;
import team.seekers.hula.record.wind.entity.dto.WindQueryDTO;
import team.seekers.hula.record.wind.entity.vo.QuestionSpaceListVO;
import team.seekers.hula.record.wind.entity.vo.WindListVO;
import team.seekers.hula.record.wind.entity.vo.WindSpaceListVO;
import team.seekers.hula.record.wind.mapper.WindMapper;
import team.seekers.hula.question.answer.service.AnswerService;
import team.seekers.hula.question.point.service.PointService;
import team.seekers.hula.question.question.entity.dao.QuestionDO;
import team.seekers.hula.question.question.service.QuestionService;
import team.seekers.hula.question.questionUser.service.QuestionUserService;
import team.seekers.hula.auth.service.MindUtils;
import team.seekers.hula.teamwork.team.teamUser.service.TeamUserService;
import team.seekers.hula.teamwork.todo.entity.dao.TodoDO;
import team.seekers.hula.teamwork.todo.service.TodoService;
import team.seekers.hula.user.user.service.UserService;
import team.seekers.hula.user.userData.service.UserDataService;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 一个输出，可以是提出一个问题、提出一个观点、写出一个回答、写一个flomo 服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-02-15
 */
@Service
public class WindService extends ServiceImpl<WindMapper, WindDO> {

    @Autowired
    @Lazy
    private IslandPostService postService;

    @Autowired
    @Lazy
    private SectionContentCommentService sectionContentCommentService;

    @Autowired
    @Lazy
    private SectionTalkService sectionTalkService;

    @Autowired
    @Lazy
    private UserService userService;

    @Autowired
    private UserDataService userDataService;

    @Autowired
    @Lazy
    private TeamUserService teamUserService;

    @Autowired
    @Lazy
    private IslandService islandService;

    @Autowired
    @Lazy
    private CourseManageService courseManageService;

    @Autowired
    @Lazy
    private QuestionService questionService;

    @Autowired
    @Lazy
    private PointService pointService;

    @Autowired
    @Lazy
    private AnswerService answerService;

    @Autowired
    @Lazy
    private QuestionUserService questionUserService;

    @Autowired
    @Lazy
    private TodoService todoService;

    @Autowired
    @Lazy
    private HistoryService historyService;

    //动作改变维护表
    public void addWind(WindTypeEnum type,String linkId,Integer visibility) {
        WindDO windDO = new WindDO();
        windDO.setUserId(MindUtils.getUserId());
        windDO.setLinkId(linkId);
        windDO.setType(type);
        windDO.setVisibility(visibility);

        if(type.equals(WindTypeEnum.FINISH_TODO_TEAM)){
            TodoDO todoDO = todoService.getById(linkId);
            windDO.setHulaCoin(todoDO.getHulaCoin());
        }else if(type.equals(WindTypeEnum.FINISH_DECISION)){
            Double hulaCoin = 0.0;
            Double hulaScore = 0.0;

            HistoryInfoVO historyInfoVO = historyService.info(linkId);
            for (HistoryUserVO historyUser : historyInfoVO.getHistoryUsers()) {
                if(historyUser.getUserInfo().getId().equals(MindUtils.getUserId())){
                    hulaCoin = historyUser.getHulaCoin();
                    hulaScore = historyUser.getHulaScore();
                }
            }
            windDO.setHulaCoin(hulaCoin);
            windDO.setHulaScore(hulaScore);
        }else{
            windDO.setHulaCoin(type.getHulaCoin());
            windDO.setHulaScore(type.getHulaScore());
        }


        save(windDO);

        // 用户hula分和hula币修改
        userDataService.addCoinAndScore(type.getHulaCoin(),type.getHulaScore());
    }

    public void updateVisibility(WindTypeEnum type, String linkId,Integer visibility) {
        lambdaUpdate()
                .eq(WindDO::getType, type.getType())
                .eq(WindDO::getLinkId, linkId)
                .set(WindDO::getVisibility,visibility)
                .update();
    }

    public void removeWind(WindTypeEnum type, String linkId) {
        WindDO windDO = lambdaQuery().eq(WindDO::getType, type).eq(WindDO::getLinkId, linkId).one();
        // 恢复hula分和hula币修改
        userDataService.addCoinAndScore(-windDO.getHulaCoin(),-windDO.getHulaScore());
        removeById(windDO.getId());
    }

    public PageResult<WindListVO> pageOrderByTime(WindQueryDTO windQueryDTO) {

        LambdaQueryChainWrapper<WindDO> wrapper = lambdaQuery().select()
                .orderByDesc(WindDO::getGmtCreate)
                .eq(WindDO::getUserId,windQueryDTO.getUserId())
                .ne(WindDO::getType,7);// 去掉待办

        if(windQueryDTO.getType() != 0)
            wrapper.eq(WindDO::getType, windQueryDTO.getType());


        if(windQueryDTO.getVisibility() != null){
            if(windQueryDTO.getVisibility() == 1){
                wrapper.eq(WindDO::getVisibility,1);
            }else {
                wrapper.ge(WindDO::getVisibility,windQueryDTO.getVisibility());
            }
        }

        Page<WindDO> page = wrapper.page(new Page<>(windQueryDTO.getPageNow(),windQueryDTO.getPageSize())) ;
        if(page.getTotal() == 0){
            return new PageResult<>();
        }

        List<WindListVO> list = new ArrayList<>();
        for (WindDO record : page.getRecords()) {
            WindListVO windListVO = new WindListVO();
            windListVO.setId(record.getId());
            windListVO.setType(record.getType().getValue());
            windListVO.setGmtCreate(record.getGmtCreate());
            windListVO.setUserInfo(userService.getFollowInfoVO(record.getUserId(),MindUtils.getUserId()));

            switch (record.getType()){
                case ADD_MEMORY:
                case ADD_POST:
                case ADD_ARTICLE:
                    windListVO.setPostInfoVO(postService.info(record.getLinkId()));
                    break;
                case ADD_COMMENT:
                case ADD_REPLAY:
                    windListVO.setCommentListVO(sectionContentCommentService.get(record.getLinkId()));
                    break;
                case ADD_TALK:
                    windListVO.setTalkListVO(sectionTalkService.get(record.getLinkId()));
                    break;
            }
            list.add(windListVO);
        }

        return new PageResult<>(page.getTotal(),list);
    }

    public List<WindSpaceListVO> listAdminSpace(String userId) {
        ArrayList<WindSpaceListVO> windSpaceListVOS = new ArrayList<>();
        List<CourseManageListVO> courseManageListVOS = courseManageService.listMyAdmin(userId);
        if(courseManageListVOS.size() == 0){
            return new ArrayList<>();
        }
        for (CourseManageListVO courseManageListVO : courseManageListVOS) {
            windSpaceListVOS.add(
                    WindSpaceListVO.builder()
                            .type(WindSpaceTypeEnum.COURSE.getType())
                            .id(courseManageListVO.getId())
                            .name(courseManageListVO.getName())
                            .cover(courseManageListVO.getCover())
                            .description(courseManageListVO.getDescription())
                            .build()
            );
        }
        List<IslandListVO> islandListVOS = islandService.listMyAdmin(userId);
        for (IslandListVO islandListVO : islandListVOS) {
            windSpaceListVOS.add(
                    WindSpaceListVO.builder()
                            .type(islandListVO.getType())
                            .id(islandListVO.getId())
                            .name(islandListVO.getName())
                            .cover(islandListVO.getBackground())
                            .description(islandListVO.getDescription())
                            .build()
            );
        }
        return windSpaceListVOS;
    }


    public List<QuestionSpaceListVO> listAdminQuestion(String userId) {
        // 查询加入的团队
        List<String> teamIds = teamUserService.listMeInIds(userId);

        List<QuestionDO> questionDOList = questionService.lambdaQuery().eq(QuestionDO::getUserId, userId).or().in(QuestionDO::getTeamId, teamIds).list();
        if(questionDOList == null || questionDOList.size() == 0){
            return new ArrayList<>();
        }

        List<QuestionSpaceListVO> list = new ArrayList<>();
        for (QuestionDO record : questionDOList) {
            QuestionSpaceListVO questionListVO = new QuestionSpaceListVO();
            BeanUtils.copyProperties(record,questionListVO);

            questionListVO.setPoints(pointService.listTwo(record.getId()));

            questionListVO.setFollowerCount(questionUserService.countFollower(record.getId()));
            questionListVO.setPointCount(pointService.countByQuestionId(record.getId()));
            questionListVO.setAnswerCount(answerService.countByQuestionId(record.getId()));

            questionListVO.setIsFollowed(questionUserService.hasFollow(record.getId(),MindUtils.getUserId()));
            list.add(questionListVO);
        }
        return list;
    }
}
